const OrderModel = require("../models/orderModel");
const addressModel = require("../models/addressModel");
const ShopItemModel = require("../models/shopItemModel");

async function createOrder(username, requestBody) {
  const { shopName, addressId, isCanceld, shopId, products } = requestBody;
  const addressInfo = await addressModel.findById(addressId.toString());
  /**
   * productArr = [
   * {
            id:"商品id",
            num:5
        }
   * ]
   */
  const IdArray = products.map((item) => item.id);
  const productList = await ShopItemModel.find({
    shopId,
    _id: {
      $in: IdArray,
    },
  });
  console.log(productList);
  const prodectWithSales = productList.map((item) => {
    let salenumArr = products.filter(
      (innerItem) => innerItem.id === item._id.toString()
    );
    let salenum = salenumArr[0].num;
    return { product: item, orderSales: salenum };
  });
  console.log(prodectWithSales);

  const res = await OrderModel.create({
    username,
    shopName,
    shopId,
    isCanceld,
    address: addressInfo,
    products: productList,
  });
  return res;
}

async function getOrders(username) {
  const res = await OrderModel.find({ username });
  return res;
}

module.exports = {
  createOrder,
  getOrders,
};
